<template>
  <el-dialog
    :close-on-click-modal="false"
    title="Add Operator"
    width="680px"
    @close="handleClose"
  >
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule" label-position="top">
      <el-form-item :label="$t('operator.name')" prop="name">
        <el-input
          v-model="dataForm.name"
          maxlength="128"
          minlength="5"
          placeholder="Operator Name"
          show-word-limit
          clearable
          @blur="() => (dataForm.name = dataForm.name.trim())"
        />
      </el-form-item>
      <el-form-item :label="$t('operator.email')" prop="email">
        <el-input
          v-model="dataForm.email"
          maxlength="128"
          placeholder="E-mail"
          show-word-limit
          clearable
          @blur="() => (dataForm.email = dataForm.email.trim())"
        />
      </el-form-item>
      <el-form-item :label="$t('operator.platform')" prop="platCodes">
        <el-select
          v-model="dataForm.platCodes"
          multiple
          :placeholder="$t('operator.platform')"
          class="w-full"
        >
          <el-option v-for="item in platcodeList" :key="item" :label="item" :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('operator.level')" prop="levelCode">
        <el-select v-model="dataForm.levelCode" clearable class="w-full">
          <el-option
            v-for="item in levelList"
            :key="item.levelCode"
            :value="item.levelCode"
            :label="item.levelName"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('operator.levelExpirationTime')" prop="expireTime">
        <el-date-picker
          v-model="dataForm.expireTime"
          type="date"
          value-format="timestamp"
          :placeholder="$t('operator.expireTimeTip')"
          style="width: 96%"
        />
        <span class="ml-2">
          <el-tooltip
            class="item"
            effect="dark"
            :content="$t('operator.leverExpireTimeTip')"
            placement="top"
          >
            <svg-icon icon-class="Warning" />
          </el-tooltip>
        </span>
      </el-form-item>
      <el-form-item :label="$t('operator.mapType')">
        <el-select v-model="dataForm.mapType" @change="mapSelect" style="width: 100%">
          <el-option
            v-for="item in mapList"
            :key="item.mapType"
            :value="item.mapType"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('operator.mapKey')" prop="mapKey">
        <div>
          <el-radio
            v-model="radio"
            label="1"
            size="small"
            style="cursor: pointer; margin-right: 10px"
            >{{ $t("operator.defaulTag") }}</el-radio
          >
        </div>
        <div>
          <el-radio v-model="radio" label="2">
            <el-input
              v-model="dataForm.mapKey"
              placeholder="key"
              maxlength="128"
              show-word-limit
              clearable
              @blur="() => (dataForm.mapKey = dataForm.mapKey.trim())"
              class="w-full"
            />
          </el-radio>
        </div>
      </el-form-item>
      <el-form-item :label="$t('customer.customerLabel')">
        <el-input v-model="dataForm.oaCustomerName" readonly>
          <template #append>
            <el-button style="font-size: 20px" text @click="openOaCustomer">
              <svg-icon icon-class="User" /></el-button
          ></template>
          <!--              <template slot="append">-->
          <!--                <button type="primary" ></button>-->
          <!--              </template>-->
        </el-input>
        <!--          <el-checkbox v-model="isOversea" style="margin-left: 20px">海外客户</el-checkbox>-->
      </el-form-item>
      <el-form-item :label="$t('operator.country')" prop="countryCode">
        <el-select
          v-model="dataForm.countryCode"
          filterable
          :placeholder="$t('operator.country')"
          style="width: 100%"
        >
          <el-option
            v-for="item in countryData"
            :key="item.countryCode3"
            :label="$t('country_or_region.' + item.countryCode3)"
            :value="item.countryCode3"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('operator.address')" prop="address">
        <el-input
          v-model="dataForm.address"
          maxlength="128"
          show-word-limit
          clearable
          @blur="() => (dataForm.address = dataForm.address.trim())"
        />
      </el-form-item>
      <el-form-item :label="$t('operator.contactName')" prop="address">
        <el-input
          v-model="dataForm.contactName"
          maxlength="64"
          show-word-limit
          clearable
          @blur="() => (dataForm.contactName = dataForm.contactName.trim())"
        />
      </el-form-item>
      <el-form-item :label="$t('operator.mobile')" prop="mobile">
        <el-input
          v-model="dataForm.mobile"
          maxlength="16"
          placeholder="Mobile"
          show-word-limit
          clearable
          @blur="() => (dataForm.mobile = dataForm.mobile.trim())"
        />
      </el-form-item>
      <el-form-item :label="$t('common.remark')" prop="remark">
        <el-input
          v-model="dataForm.remark"
          maxlength="256"
          show-word-limit
          clearable
          @blur="() => (dataForm.remark = dataForm.remark.trim())"
        />
      </el-form-item>
      <el-form-item>
        <el-upload
          ref="upload"
          action="#"
          accept=".crt"
          :on-remove="handleRemove"
          :on-change="handleChange"
          :file-list="fileList"
          :auto-upload="false"
        >
          <!--            <div slot="tip" class="el-upload__tip">
              {{ $t('operator.upload_cert_tip') }}
            </div>-->
          <template #trigger>
            <el-button type="primary">{{
              $t("operator.chooseFileBtn")
            }}</el-button></template
          >
        </el-upload>
      </el-form-item>
      <div v-show="showCN">
        <el-divider />
        <el-form-item style="color: #00ff80" :label="$t('operator.issuer_cn')">
          <el-input type="textarea" v-model="issuerCn" rows="6" :disabled="true" />
        </el-form-item>
        <el-divider />
        <el-form-item :label="$t('operator.subject_cn')">
          <el-input type="textarea" v-model="subjectCn" rows="7" :disabled="true" />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button text @click="handleClose">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" :loading="dataListLoading" @click="dataFormSubmit()">{{
          $t("common.confirm")
        }}</el-button>
      </span></template
    >
    <oa-customer-list v-model="oaCustomerListVisible" ref="oaCustomerList" />
  </el-dialog>
</template>

<script>
import {
  getCountryList,
  addOperator,
  getPlatCode,
  checkCert,
  checkOperator,
  examineOperator,
} from "@/api/operator";
import countryJson from "@/assets/static/country.json";
import { getMapList } from "@/utils";
import OaCustomerList from "./oa-customer-list";
import { getSystemMenuList } from "@/api/system-menu";
// import {isEmail} from '@/utils/validate'

export default {
  components: {
    OaCustomerList,
  },
  data() {
    const validatePlatcode = (rule, value, callback) => {
      if (!value || value.length < 1) {
        callback(new Error(this.$t("operator.platcode_tip")));
      } else {
        callback();
      }
    };
    const validateLevelcode = (rule, value, callback) => {
      if (!value || value.length < 1) {
        callback(new Error(this.$t("operator.levelcode_tip")));
      } else {
        callback();
      }
    };
    /* var validateEmail = (rule, value, callback) => {
      if (!isEmail(value.trim())) {
        callback(new Error(this.$t('user.emailError')))
      } else {
        callback()
      }
    } */
    /* var validateMobile = (rule, value, callback) => {
      if (!isMobile(value) && value) {
        callback(new Error(this.$t('userAddUpdate.mobileError')))
      } else {
        callback()
      }
    } */
    return {
      dataListLoading: false,
      oaCustomerListVisible: false,
      showCN: false,
      clickDisabled: true,
      countryData: countryJson,
      fileList: [],
      levelList: [],
      platcodeList: [],
      issuerCn: "",
      subjectCn: "",
      dataForm: {
        username: "",
        name: "",
        contactName: "",
        email: "",
        address: "",
        gmtTime: "",
        lang: "",
        platCodes: [],
        mobile: "",
        remark: "",
        countryCode: "",
        levelCode: "STANDARD_LEVEL",
        expireTime: null,
        mapType: "MAP_BOX",
        mapKey: "",
        oaCustomerName: "",
        oaCustomerCode: "",
      },
      radio: "1",
      id: null,
      cmdTypeCodeList: [],
      mapList: [],
      langList: [
        { value: "en_US", lable: "English" },
        { value: "zh_CN", lable: "Simplified Chinese" },
        { value: "zh_HK", lable: "Traditional Chinese" },
        { value: "pt_BR", lable: "Portuguese" },
        { value: "ru_RU", lable: "Russian" },
        { value: "tr_TR", lable: "Turkish" },
        { value: "hi_IN", lable: "Hindi" },
        { value: "uk_UA", lable: "Ukrainian" },
        { value: "vi_VN", lable: "Vietnamese" },
        { value: "tl_PH", lable: "Tagalog" },
        { value: "ar_EG", lable: "Arabic" },
        { value: "th_TH", lable: "Thai" },
      ],
      gmtTimeList: [
        { val: "GMT+00:00", label: "GMT+00:00" },
        { val: "GMT+01:00", label: "GMT+01:00" },
        { val: "GMT+02:00", label: "GMT+02:00" },
        { val: "GMT+03:00", label: "GMT+03:00" },
        { val: "GMT+04:00", label: "GMT+04:00" },
        { val: "GMT+05:00", label: "GMT+05:00" },
        { val: "GMT+06:00", label: "GMT+06:00" },
        { val: "GMT+07:00", label: "GMT+07:00" },
        { val: "GMT+08:00", label: "GMT+08:00" },
        { val: "GMT+09:00", label: "GMT+09:00" },
        { val: "GMT+10:00", label: "GMT+10:00" },
        { val: "GMT+11:00", label: "GMT+11:00" },
        { val: "GMT-12:00", label: "GMT-12:00" },
        { val: "GMT-11:00", label: "GMT-11:00" },
        { val: "GMT-10:00", label: "GMT-10:00" },
        { val: "GMT-09:00", label: "GMT-09:00" },
        { val: "GMT-08:00", label: "GMT-08:00" },
        { val: "GMT-07:00", label: "GMT-07:00" },
        { val: "GMT-06:00", label: "GMT-06:00" },
        { val: "GMT-05:00", label: "GMT-05:00" },
        { val: "GMT-04:00", label: "GMT-04:00" },
        { val: "GMT-03:00", label: "GMT-03:00" },
        { val: "GMT-02:00", label: "GMT-02:00" },
        { val: "GMT-01:00", label: "GMT-01:00" },
      ],
      dataRule: {
        name: [
          {
            required: true,
            message: this.$t("common.nullInputTip"),
            trigger: "blur",
          },
        ],
        contactName: [
          {
            required: true,
            message: this.$t("common.nullInputTip"),
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: this.$t("common.nullInputTip"),
            trigger: "blur",
          },
          {
            type: "email",
            required: true,
            message: this.$t("common.email_format_error"),
            trigger: "blur",
          },
        ],
        /* address: [{required: true, message: 'Address be empty', trigger: 'change'}], */
        gmtTime: [
          {
            required: true,
            message: this.$t("common.nullInputTip"),
            trigger: "blur",
          },
        ],
        lang: [
          {
            required: true,
            message: this.$t("common.nullInputTip"),
            trigger: "blur",
          },
        ],
        /* mobile: [{required: true, message: 'Mobile be empty', trigger: 'change'},
                  {validator: validateMobile, trigger: 'change'}], */
        countryCode: [
          {
            required: true,
            message: this.$t("common.nullInputTip"),
            trigger: "blur",
          },
        ],
        // mapKey: [
        //   {
        //     required: true,
        //     message: this.$t('common.nullInputTip'),
        //     trigger: 'blur'
        //   }
        // ],
        platCodes: [{ required: true, trigger: "manual", validator: validatePlatcode }],
        levelCode: [{ required: true, trigger: "manual", validator: validateLevelcode }],
      },
    };
  },
  created() {
    this.mapList = getMapList();
    // this.levelList = this.$t('operator.level_list')
  },
  methods: {
    init() {
      getCountryList()
        .then((data) => {
          this.countryData = data;
        })
        .catch((e) => {
          this.$confirmError(e);
        });
      this.getPlatCode();
      this.getLevelInfo();
      this.clickDisabled = true;
      this.dataListLoading = false;
      this.showCN = false;
    },
    getLevelInfo() {
      let params = {
        characterCode: "",
        levelCode: "",
        pageNo: 1,
        pageSize: 100,
      };
      getSystemMenuList(params)
        .then((res) => {
          this.levelList = res.data;
        })
        .catch((e) => {
          this.$confirmError(e);
        });
    },
    getPlatCode() {
      getPlatCode("OPERATOR")
        .then((res) => {
          this.platcodeList = res;
          this.dataForm.platCodes = res;
        })
        .catch((err) => {
          this.$confirmError(err);
        });
    },
    mapSelect() {
      this.dataForm.mapKey = "";
    },
    defaultKeyClick() {
      if (this.dataForm.mapType === "MAP_BOX") {
        this.dataForm.mapKey = this.mapList[0].mapKey;
      } else if (this.dataForm.mapType === "GOOGLE") {
        this.dataForm.mapKey = this.mapList[1].mapKey;
      } else if (this.dataForm.mapType === "BAIDU") {
        this.dataForm.mapKey = this.mapList[2].mapKey;
      }
    },
    dataFormSubmit() {
      console.log(this.dataForm);
      console.log("oaCustomerCode:" + this.dataForm.oaCustomerCode);
      console.log("oaCustomerName:" + this.dataForm.oaCustomerName);
      if (this.radio === "2" && this.dataForm.mapKey === "") {
        this.$confirm(this.$t("operator.map_not_null"), this.$t("page.tip"), {
          confirmButtonText: this.$t("page.confirm"),
          cancelButtonText: this.$t("page.cancel"),
          type: "warning",
        });
        return;
      }
      if (this.fileList.length === 0) {
        return this.$message.error(this.$t("operator.upload_cert_tip"));
      }
      if (this.dataForm.name.length < 5) {
        return this.$message.error("Operator name should be no less than 5 characters.");
      }
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          if (
            this.dataForm.oaCustomerCode === "" ||
            this.dataForm.oaCustomerCode === ""
          ) {
            this.$confirm(this.$t("operator.oaInfoIsNullConfirm"), "", {
              confirmButtonText: this.$t("common.confirm"),
              cancelButtonText: this.$t("common.cancel"),
              type: "warning",
            }).then(() => {
              this.createOperatorHandle();
            });
          } else {
            this.createOperatorHandle();
          }
        }
      });
    },
    handleClose() {
      this.$emit("close");
    },
    handleFileChange(file, fileList) {
      this.$refs.upload.clearFiles();
      const extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (extension !== "crt") {
        return this.$message.warning("Only the suffix can be uploaded is crt");
      }
      if (fileList.length > 1) {
        fileList.shift();
      }
      this.fileList = fileList;
    },
    handleRemove(file, fileList) {
      fileList.shift();
      this.showCN = false;
    },
    handlePreview(file) {},
    handleChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.shift();
      }
      this.fileList = fileList;
      const extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (extension !== "crt") {
        fileList.shift();
        return this.$message.warning("Only the suffix can be uploaded is crt");
      }
      console.log(this.fileList);
      const certData = new FormData();
      certData.append("file", this.fileList[0].raw);
      checkCert(certData)
        .then((res) => {
          this.showCN = true;
          this.issuerCn = res.issuerCn;
          this.subjectCn = res.subjectCn;
          console.log(res);
        })
        .catch((data) => {
          this.$message.error(data.message);
          this.fileList = [];
        });
    },
    handleV4Cert(issuerCN) {
      const h = this.$createElement;
      this.$msgbox({
        title: this.$t("page.tip"),
        message: h("p", null, [
          // this.$t('operator.tipDeleteEmail', { email: email })
          h(
            "i",
            { style: "color: red" },
            this.$t("operator.tip_issuer_cn", { issuerCN: issuerCN })
          ),
        ]),
        showCancelButton: true,
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            setTimeout(() => {
              done();
              setTimeout(() => {
                instance.confirmButtonLoading = false;
              }, 300);
            }, 300);
          } else {
            done();
          }
        },
      }).then((action) => {
        this.systemRegisterOperator();
      });
    },
    openOaCustomer() {
      this.oaCustomerListVisible = true;
      this.$nextTick(() => {
        this.$refs.oaCustomerList.init();
      });
    },
    closeOaCustomerList(customer) {
      console.log(customer);
      this.dataForm.oaCustomerName = customer.customerName;
      this.dataForm.oaCustomerCode = customer.customerCode;
    },
    createOperatorHandle() {
      this.dataListLoading = true;
      const formData = new FormData();
      if (this.radio === "1") {
        formData.append("isDefaultMapKey", true);
      } else {
        formData.append("mapKey", this.dataForm.mapKey);
        formData.append("isDefaultMapKey", false);
      }
      formData.append("file", this.fileList[0].raw);
      formData.append("username", this.dataForm.email);
      formData.append("name", this.dataForm.name);
      formData.append("contactName", this.dataForm.contactName);
      formData.append("platCodes", this.dataForm.platCodes);
      formData.append("email", this.dataForm.email);
      formData.append("address", this.dataForm.address);
      formData.append("gmtTime", this.dataForm.gmtTime);
      formData.append("lang", this.dataForm.lang);
      formData.append("mobile", this.dataForm.mobile);
      formData.append("remark", this.dataForm.remark);
      formData.append("countryCode", this.dataForm.countryCode);
      formData.append("levelCode", this.dataForm.levelCode);
      formData.append("oaCustomerCode", this.dataForm.oaCustomerCode);
      formData.append("oaCustomerName", this.dataForm.oaCustomerName);
      if (this.dataForm.expireTime !== null) {
        formData.append("expireTime", this.dataForm.expireTime);
      }
      formData.append("mapType", this.dataForm.mapType);
      addOperator(formData)
        .then((res) => {
          this.dataListLoading = false;
          this.$emit("update:model-value", false);
          this.$message.success(this.$t("common.operate_success"));
          this.$emit("refreshDataList");
        })
        .catch((data) => {
          this.dataListLoading = false;
          console.log(data);
          this.$message.error(data.message);
          this.fileList = [];
          this.showCN = false;
        });
    },
  },
};
</script>

//
<style lang="scss" scoped>
// .el-divider {
//   margin: 10px 0;
// }
</style>
